package com.loeng.framework.quartz.config;

import com.alibaba.ttl.TtlRunnable;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * @author loeng
 * @date 2025/4/15 21:37
 */
@AutoConfiguration
@EnableAsync
public class LoengAsyncAutoConfiguration {

    /**
     * 对 Spring 容器中的 ThreadPoolTaskExecutor 类型的 Bean 进行后处理
     * 确保线程池提交的任务能够支持 TransmittableThreadLocal（简称 TTL），
     * 从而实现线程上下文信息的跨线程传递
     *
     * @return BeanPostProcessor
     */
    @Bean
    public BeanPostProcessor threadPoolTaskExecutorPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
                if (!(bean instanceof ThreadPoolTaskExecutor)) {
                    return bean;
                }

                // 修改提交的任务，接入 TransmittableThreadLocal
                ThreadPoolTaskExecutor executor = (ThreadPoolTaskExecutor) bean;
                executor.setTaskDecorator(TtlRunnable::get);
                return executor;
            }
        };
    }

}
